<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 会员消息类
 * @package  module/base/customer
 * @author   create by allen.qiang
 * @version 1.0
 */

class custMessage{

    /**
     * 查询会员消息
     */
    public function searchCustMessageMaster( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //SQL字段类型字符串
        $params_type = '';

        //SQL字段值数组
        $params_array = array();

        //会员号
        if (isset($arg_array['message_id']) && is_numeric($arg_array['message_id'])) {
            $sql .= ' AND message_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['message_id'];
        }

        //标题
        if (isset($arg_array['message_title']) && !empty($arg_array['message_title'])) {
            $sql .= ' AND message_title LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['message_title'] . '%';
        }

        //回复时间
        if (isset($arg_array['message_content']) && !empty($arg_array['message_content'])) {
            $sql .= ' AND message_content = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['message_content'];
        }


        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM cust_message_master ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;
                //分页bug处理
                if ($arg_array['count'] < $arg_array['rp']) {

                    $arg_array['page'] = 1;
                }
                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }


            //查询分类信息
            $search_sql = 'SELECT * FROM cust_message_master ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach ($temp_item_array as &$item) {

                //用户信息数组
                $item_array[]  = array(
                    'createTime' => $item->createTime,
                    'message_id'	=> 	$item->message_id,
                    'message_title'	=> 	$item->message_title,
                    'message_content'	=> 	$item->message_content
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 添加、修改会员消息
     *
     */
    public function editMessageMaster ( $arg_array ) {

        global $G_SHOP;

        //检查参数
        if (!isset( $arg_array['message_title'],$arg_array['message_content']) && !is_numeric($arg_array['message_id'])){
            return array('message'=>'参数错误','code'=> 400);
        }

        if (empty($arg_array['message_title']))

            return array( 'code' => 400, 'message' => '会员消息标题不能为空' );

        if (empty($arg_array['message_content']))

            return array( 'code' => 400, 'message' => '会员消息内容不能为空' );

        $creator                          = $arg_array['creator'];
        $message_id                       = $arg_array['message_id'] ;
        $message_titlee	                  = $arg_array['message_title'] ;
        $message_content                  = $arg_array['message_content'] ;

        try{

            $message_master = new entity('cust_message_master');

            if ($message_id == 0) {
                $message_master->creator = $creator;
                $message_master->message_id = generate_seqno('seqno_message');
            } else {
                $message_master->message_id = $message_id;
                if (!$G_SHOP->DBCA->fetch($message_master)) {
                    throw new Exception('会员消息信息没有找到', 404);
                }
            }

            //保存会员消息信息
            $message_master->message_title = $message_titlee;
            $message_master->message_content = $message_content;
            $G_SHOP->DBCA->save( $message_master );

            if ($message_id > 0) {
                return array( 'code' => 200, 'message' => '会员消息修改成功' );
            } else {
                return array( 'code' => 200, 'message' => '会员消息保存成功' );
            }

        }catch (Exception $e) {
            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
    }

    /**
     * 删除会员消息
     * @param array $pay_array 会员消息ID数组
     * @return array
     */
    public function deleteMessageMaster ( $pay_array ) {

        global $G_SHOP;

        if (!isset($pay_array) || !is_array($pay_array) || empty($pay_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            foreach($pay_array as &$message_id) {



                //查询会员消息方式
                $pay_obj = new entity('cust_message_master');
                $pay_obj->message_id = $message_id;
                if (!$G_SHOP->DBCA->fetch($pay_obj)) {
                    throw new Exception('会员消息信息没有找到', 404);
                }

                //删除会员消息信息
                $G_SHOP->DBCA->delete($pay_obj);

            }

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '删除会员消息成功' );

        } catch ( Exception $e ) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }


    /**
     * 发放会员消息
     * @param int $message_id 会员消息ID
     * @param array $c_array 会员名数组
     * $c_array = array( '会员名', '会员名', '会员名', '会员名' )
     * @return array
     */
    public function createCustMessage( $message_id, $c_array = array() ) {

        global $G_SHOP;

        if (!isset($message_id) || !is_numeric($message_id)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $message_obj = new entity('cust_message_master');
            $message_obj->message_id = $message_id;
            if (!$G_SHOP->DBCA->fetch($message_obj) ) {
                throw new Exception('会员消息信息没有找到', 404);
            }


            $sql = 'INSERT INTO cust_message(uuid,timeStamp,creator,createTime,custID,pcustID,message_id,message_title) VALUES ';

            $first = 1;

            foreach($c_array as &$cust_id_array) {

                //判断会员是否存在
                $cust_master = new entity('cust_master');
                $cust_master->custID = $cust_id_array[0];
                if ( !$G_SHOP->DBCA->fetch($cust_master) ) {
                    continue;
                }

                //判断消息是否已经发送过
                $cust_message = new entity("cust_message");
                $cust_message->pcustID = $cust_master->pcustID;
                $cust_message->message_id = $message_id;
                if ( $G_SHOP->DBCA->fetch($cust_message) ) {
                    continue;
                }



                if ($first) {
                    $sql .= sprintf('("%s","%s","%s","%s","%s","%s","%s","%s")',
                            make_uuid(), $G_SHOP->sys_datetime, 'system__publish', $G_SHOP->sys_datetime, $cust_master->custID,
                            $cust_master->pcustID, $message_obj->message_id, $message_obj->message_title);
                } else {
                    $sql .= sprintf(',("%s","%s","%s","%s","%s","%s","%s","%s")',
                            make_uuid(), $G_SHOP->sys_datetime, 'system__publish', $G_SHOP->sys_datetime, $cust_master->custID,
                            $cust_master->pcustID, $message_obj->message_id, $message_obj->message_title);
                }
                $first = 0;

            }

            $G_SHOP->DBCA->execute($sql);

            return array( 'code' => 200, 'message' => '会员消息生成成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }


    /**
     * 查询会员发送消息
     */
    public function searchCustMessage( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //SQL字段类型字符串
        $params_type = '';

        //SQL字段值数组
        $params_array = array();

        //会员名
        if (isset($arg_array['custID']) && !empty($arg_array['custID'])) {
            $sql .= ' AND custID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['custID'];
        }

        //会员消息ID
        if (isset($arg_array['message_id']) && is_numeric($arg_array['message_id'])) {
            $sql .= ' AND message_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['message_id'];
        }

        //会员号
        if (isset($arg_array['pcustID']) && !empty($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //消息标题
        if (isset($arg_array['message_title']) && !empty($arg_array['message_title'])) {
            $sql .= ' AND message_title = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['message_title'];
        }

        //是否已读
        if (isset($arg_array['is_read']) && in_array($arg_array['is_read'], array( '0', '1' ))) {
            $sql .= ' AND  is_read = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['is_read'];
        }

        //是否已回复
        if (isset($arg_array['is_reply']) && in_array($arg_array['is_reply'], array( '0', '1' ))) {
            $sql .= ' AND  is_reply = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['is_reply'];
        }

        //回复开始时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate']) ) {
            $sql .= ' AND reply_time >=?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'] ;
        }
        //回复结束时间
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate']) ) {
            $sql .= ' AND reply_time <=?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'] ;
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

            //统计数量
            $search_sql = 'SELECT COUNT(*) AS item_count FROM cust_message ' . $sql;
            $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            $item_count = $count_array[0]->item_count;
            if ($item_count == 0) {
                $arg_array['count'] = 0;
                return null;
            }

            $arg_array['count'] = $item_count;
            //分页bug处理
            if ($arg_array['count'] < $arg_array['rp']) {

                $arg_array['page'] = 1;
            }
            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            //分页
            if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                $arg_array['page'] = 1;

            $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

        } else {

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

        }


        //查询分类信息
        $search_sql = 'SELECT * FROM cust_message ' . $sql;
        $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
        if (!$temp_item_array)
            return null;

        $item_array = array();
        foreach ($temp_item_array as &$item) {

            //用户信息数组
            $item_array[]  = array(
                'uuid'	    => 	$item->uuid,
                'timeStamp'	=>	$item->timeStamp,
                'creator' 	=> 	$item->creator,
                'createTime' => $item->createTime,
                'custID' => $item->custID,
                'pcustID' => $item->pcustID,
                'message_id'	=> 	$item->message_id,
                'message_title'	=> 	$item->message_title,
                'is_read' => $item->is_read,
                'is_reply' => $item->is_reply,
                'reply_time' =>$item->reply_time,
                'reply_content'	=> 	$item->reply_content
            );
        }

        return $item_array;

    }

    /**
     * 删除会员发送消息
     * @param array $pay_array 会员发送消息ID数组
     * @return array
     */
    public function deleteMessage ( $pay_array ) {

        global $G_SHOP;

        if (!isset($pay_array) || !is_array($pay_array) || empty($pay_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            foreach($pay_array as &$uuid) {
                //查询会员发送消息方式
                $pay_obj = new entity('cust_message');
                $pay_obj->uuid = $uuid;
                if (!$G_SHOP->DBCA->fetch($pay_obj)) {
                    throw new Exception('会员发送消息信息没有找到', 404);
                }
                //删除会员发送消息信息
                $G_SHOP->DBCA->delete($pay_obj);

            }

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '删除会员发送消息成功' );

        } catch ( Exception $e ) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 更新会员消息为“已读”
     * @param int $pcustID 会员号
     * @param int $message_id 消息id
     * @return array
     */
    public function updateMessageRead( $pcustID, $message_id ) {

        global $G_SHOP;

        if (!isset($pcustID, $message_id) || !quanli_is_int($pcustID) || !quanli_is_int($message_id)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            //查询会员消息
            $message_obj = new entity('cust_message');
            $message_obj->pcustID = $pcustID;
            $message_obj->message_id = $message_id;
            if (!$G_SHOP->DBCA->fetch($message_obj)) {
                throw new Exception('会员消息没有找到', 404);
            }
            if ($message_obj->is_read == 1) {
                throw new Exception('会员消息已被设为已读', 404);
            }
            $message_obj->is_read = 1;
            $G_SHOP->DBCA->save($message_obj);

            return array( 'code' => 200, 'message' => '消息已读成功' );

        } catch ( Exception $e ) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 消息回复
     * @param int $pcustID 会员号
     * @param int $message_id 消息id
     * @param string $reply_content 回复内容
     * @return array
     */
    public function replyMessage( $pcustID, $message_id, $reply_content ) {

        global $G_SHOP;

        if (!isset($pcustID, $message_id) || !quanli_is_int($pcustID) || !quanli_is_int($message_id)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!isset($reply_content) || empty($reply_content)) {
            return array( 'code' => 400, 'message' => '请填写回复内容' );
        }

        try {

            //查询会员消息
            $message_obj = new entity('cust_message');
            $message_obj->pcustID = $pcustID;
            $message_obj->message_id = $message_id;
            if (!$G_SHOP->DBCA->fetch($message_obj)) {
                throw new Exception('会员消息没有找到', 404);
            }
            if ($message_obj->is_reply == 1) {
                throw new Exception('会员消息已回复', 404);
            }
            $message_obj->is_reply = 1;
            $message_obj->reply_time = $G_SHOP->sys_datetime;
            $message_obj->reply_content = $reply_content;
            $G_SHOP->DBCA->save($message_obj);

            return array( 'code' => 200, 'message' => '消息回复成功' );

        } catch ( Exception $e ) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }


    }


}